import { nextTick, onMounted, ref, unref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ElTable } from 'element-plus'
import type { TableExpose } from '../tableExpose'
import type { TableColumn, TableProps, TableSetProps } from '../types'

import type Table from '../Table.vue'

export type ParamsType = Partial<Record<string, any>>

interface UseTableConfig {
  /**
   * 是否初始化的时候请求一次
   */
  immediate?: boolean
  fetchDataApi: (params?: ParamsType) => Promise<{
    list: any[]
    total?: number
  }>
  fetchDelApi?: () => Promise<boolean>
  /**
   * 是否排序然后刷新数据
   */
  sortedThenRefresh?: boolean
}

export function useTable(config: UseTableConfig) {
  const { immediate = true, sortedThenRefresh = false } = config

  const loading = ref(false)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  const dataList = ref<any[]>([])
  const defaultSort = ref<{
    prop?: string
    order?: 'ascending' | 'descending'
  }>({})

  watch(
    () => currentPage.value,
    () => {
      methods.getList()
    },
  )

  watch(
    () => pageSize.value,
    () => {
      // 当前页不为1时，修改页数后会导致多次调用getList方法
      if (unref(currentPage) === 1) {
        methods.getList()
      }
      else {
        currentPage.value = 1
        methods.getList()
      }
    },
  )

  onMounted(() => {
    if (immediate)
      methods.getList()
  })

  // Table实例
  const tableRef = ref<typeof Table & TableExpose>()

  // ElTable实例
  const elTableRef = ref<InstanceType<typeof ElTable>>()

  const register = (
    ref: typeof Table & TableExpose,
    elRef: InstanceType<typeof ElTable>,
  ) => {
    tableRef.value = ref
    elTableRef.value = unref(elRef)
  }

  const getTable = async () => {
    await nextTick()
    const table = unref(tableRef)
    if (!table) {
      console.error(
        'The table is not registered. Please use the register method to register',
      )
    }
    return table
  }

  const methods = {
    /**
     * 获取表单数据
     */
    getList: async (params?: ParamsType) => {
      loading.value = true
      try {
        const res = await config?.fetchDataApi(params)
        console.log('fetchDataApi res', res)
        if (res) {
          dataList.value = res.list
          total.value = res.total || 0
          await nextTick()
          if (defaultSort.value.prop && defaultSort.value.order) {
            elTableRef.value?.sort(defaultSort.value.prop, defaultSort.value.order)
          }
        }
      }
      catch {
        console.log('fetchDataApi error')
      }
      finally {
        loading.value = false
      }
    },

    /**
     * @description 设置table组件的props
     * @param props table组件的props
     */
    setProps: async (props: TableProps = {}) => {
      const table = await getTable()
      table?.setProps(props)
    },

    /**
     * @description 设置column
     * @param columnProps 需要设置的列
     */
    setColumn: async (columnProps: TableSetProps[]) => {
      const table = await getTable()
      table?.setColumn(columnProps)
    },

    /**
     * @description 新增column
     * @param tableColumn 需要新增数据
     * @param index 在哪里新增
     */
    addColumn: async (tableColumn: TableColumn, index?: number) => {
      const table = await getTable()
      table?.addColumn(tableColumn, index)
    },

    /**
     * @description 删除column
     * @param field 删除哪个数据
     */
    delColumn: async (field: string) => {
      const table = await getTable()
      table?.delColumn(field)
    },

    /**
     * @description 获取ElTable组件的实例
     * @returns ElTable instance
     */
    getElTableExpose: async () => {
      await getTable()
      return unref(elTableRef)
    },

    refresh: () => {
      methods.getList()
    },

    // sortableChange: (e: any) => {
    //   console.log('sortableChange', e)
    //   const { oldIndex, newIndex } = e
    //   dataList.value.splice(newIndex, 0, dataList.value.splice(oldIndex, 1)[0])
    //   // to do something
    // }
    // 删除数据
    delList: async (idsLength: number) => {
      const { fetchDelApi } = config
      if (!fetchDelApi) {
        console.warn('fetchDelApi is undefined')
        return
      }
      ElMessageBox.confirm('是否删除所选中数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const res = await fetchDelApi()
        if (res) {
          ElMessage.success('删除成功')

          // 计算出临界点
          const current
            = unref(total) % unref(pageSize) === idsLength
            || unref(pageSize) === 1
              ? unref(currentPage) > 1
                ? unref(currentPage) - 1
                : unref(currentPage)
              : unref(currentPage)

          currentPage.value = current
          methods.getList()
        }
      })
    },
  }

  function sortChange({ column, prop, order }) {
    let truelyChange = false
    if (defaultSort.value.prop != prop || defaultSort.value.order != order) {
      truelyChange = true
    }
    defaultSort.value.prop = prop
    defaultSort.value.order = order
    if (sortedThenRefresh && truelyChange) {
      methods.getList()
    }
  }

  return {
    tableRegister: register,
    tableMethods: methods,
    tableState: {
      currentPage,
      pageSize,
      total,
      dataList,
      loading,
      defaultSort,
      sortChange,
    },
  }
}
